import React, { useState, useEffect, useCallback, useRef } from 'react';
import type { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import { Button, DatePicker, Modal } from 'antd';
import { history } from 'umi';
import moment from 'moment';

import { tenantPage, tenantChangeStatus } from '@/services/clienteleControl';
import Const from '@/utils/Const';

import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { confirm } = Modal;

const SysSettingClientele: React.FC = () => {
  const actionRef = useRef<any>();
  const ref = useRef();

  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  // 添加编辑客户
  const addEditClientele = useCallback((type, id = '') => {
    history.push({
      pathname: '/features/sysSetting/addEditClientele',
      state: {
        type,
        id,
      },
    });
  }, []);

  // 启用、停用
  const changeStatus = useCallback((type, ids) => {
    confirm({
      title: `${type === 'open' ? '启用提示信息' : '停用提示信息'}`,
      icon: <ExclamationCircleOutlined />,
      content: `${
        type === 'open'
          ? '确定启用吗？'
          : '该操作将影响当前客户的所有操作，确定停用吗？'
      }`,
      onOk() {
        console.log('OK', ids);
        tenantChangeStatus({
          ids,
          status: type === 'open' ? 1 : 0,
        }).then((res) => {
          console.log(res, '--启用停用--');
          if (res.code === Const.successCode) {
            if (actionRef.current) actionRef.current.reload();
          }
        });
      },
      onCancel() {
        console.log('Cancel', ids);
      },
    });
  }, []);

  // 全部启用、停用
  const changeAllStatus = useCallback((type, selectedRowKeys, selectedRows) => {
    let isCould = true;
    for (let item of selectedRows) {
      if (type === 'open') {
        if (+item.status !== 0) {
          isCould = false;
          break;
        }
      }
      if (type === 'close') {
        if (!(+item.status === 0 || +item.status === 4)) {
          isCould = false;
          break;
        }
      }
    }
    if (isCould && selectedRowKeys.length !== 0) {
      changeStatus(type, selectedRowKeys);
    }
  }, []);

  // 删除
  const deleteIt = useCallback(() => {
    confirm({
      title: '删除提示信息',
      icon: <ExclamationCircleOutlined />,
      content: '是否确认删除？',
      onOk() {
        console.log('删除');
      },
      onCancel() {
        console.log('取消删除');
      },
    });
  }, []);

  // 编辑
  const editClientele = useCallback((id) => {
    confirm({
      title: '编辑提示信息',
      icon: <ExclamationCircleOutlined />,
      content: '该操作将影响当前客户的所有操作，确定编辑吗？',
      onOk() {
        addEditClientele('edit', id);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }, []);

  const TableCustomDeploy = {
    componentName: 'customTable',
  };

  const requestHandle = async (params: any) => {
    let res = await tenantPage(params);
    let resData = Const.dealResDataSwitch(res);
    // console.log(resData, 'resData');
    return Promise.resolve(resData);
  };

  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    const columns: ProColumns[] = [
      // {
      //   dataIndex: 'index',
      //   title: '序号',
      //   valueType: 'indexBorder',
      // },
      {
        title: '客户编码',
        dataIndex: 'id',
        valueType: 'text',
        hideInSearch: true,
        width: 80,
      },
      {
        title: '客户名称',
        dataIndex: 'name',
        valueType: 'text',
        width: 120,
      },
      {
        title: '客户状态',
        dataIndex: 'status',
        valueEnum: Const.clienteleStatusMap,
        filters: false,
        width: 80,
      },
      {
        title: '公司全称',
        dataIndex: 'companyName',
        valueType: 'text',
        hideInSearch: true,
        width: 120,
      },
      {
        title: '开始日期',
        dataIndex: 'validFrom',
        renderFormItem: (item, { ...rest }) => (
          <RangePicker
            // style={{ width: '100%' }}
            format={Const.format}
            placeholder={['请选择', '请选择']}
          ></RangePicker>
        ),
        width: 120,
      },
      {
        title: '结束日期',
        dataIndex: 'validTo',
        renderFormItem: (item, { ...rest }) => (
          <RangePicker
            // style={{ width: '100%' }}
            placeholder={['请选择', '请选择']}
            format={Const.format}
          ></RangePicker>
        ),
        width: 120,
      },
      {
        title: '联系人',
        dataIndex: 'contactor',
        valueType: 'text',
        hideInSearch: true,
        width: 120,
      },
      {
        title: '联系电话',
        dataIndex: 'contactorPhone',
        valueType: 'text',
        hideInSearch: true,
        width: 120,
      },
      {
        title: '联系邮箱',
        dataIndex: 'contactorEmail',
        valueType: 'text',
        hideInSearch: true,
        width: 120,
      },
      {
        title: '操作',
        valueType: 'option',
        width: 200,
        fixed: 'right',
        render: (text, record, _, action) => {
          let arr = [
            <Button
              type="link"
              onClick={() => addEditClientele('view', record.id)}
            >
              详情
            </Button>,
            <Button type="link" onClick={() => editClientele(record.id)}>
              编辑
            </Button>,
          ];
          const status = +record.status;
          if (status === 0 || status === 4) {
            arr.push(
              <Button
                type="link"
                onClick={() => changeStatus('open', [record.id])}
              >
                启用
              </Button>,
            );
          } else if (status === 1) {
            arr.push(
              <Button
                type="link"
                onClick={() => changeStatus('close', [record.id])}
              >
                停用
              </Button>,
            );
          } else {
            arr.push(
              <Button type="link" disabled>
                过期
              </Button>,
            );
          }
          // arr.push(
          //   <Button type="link" onClick={() => deleteIt()}>
          //     删除
          //   </Button>,
          // );
          return arr;
        },
      },
    ];
    // rowSelection
    const tableSelectChange = (setSelectedRowKeys: any, selectedRows: any) => {
      setSelectedRowKeys(selectedRowKeys);
      setSelectedRows(selectedRows);
    };
    // const rowSelection: any = {
    //   type: 'checkbox',
    //   selectedRowKeys,
    //   onChange: tableSelectChange,
    // };
    return {
      columns,
      actionRef: actionRef,
      formRef: ref,
      request: async (params = {}, sort, filter) => {
        console.log('request请求发出', params);
        let dateArr = ['validFrom', 'validTo'];
        for (let item of dateArr) {
          if (params[item] && params[item][0] && params[item][1]) {
            const startTime = params[item][0].split(' ')[0];
            const endTime = params[item][1].split(' ')[0];
            params[item + 'Start'] = moment(startTime).valueOf();
            params[item + 'End'] = moment(endTime).valueOf();
            delete params[item];
          }
        }
        console.log('request请求发出', params);
        return requestHandle(params);
      },
      rowSelection: {
        type: 'checkbox',
      },
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) =>
          `第${range[0]}-${range[1]}条 共 ${total} 项`,
      },
      rowKey: 'id',
      toolBarRender: () => [
        <Button icon={<PlusOutlined />} onClick={() => addEditClientele('add')}>
          新增
        </Button>,
        <Button
          onClick={() => {
            changeAllStatus('open', selectedRowKeys, selectedRows);
          }}
        >
          启用
        </Button>,
        <Button
          onClick={() => {
            changeAllStatus('close', selectedRowKeys, selectedRows);
          }}
        >
          停用
        </Button>,
      ],
      scroll: { x: 900 },
    };
  };

  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };
  return (
    <div>
      <ProTable {...jsonOption}></ProTable>
    </div>
  );
};

export default SysSettingClientele;
